import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'frame_parser.dart';

const HOST = "192.168.0.113";
const PORT = 9092;

typedef MessageHandler<T> = void Function(T value);

typedef PeriodicHandler = void Function();

final socketClient = SocketClient();

class SocketClient {
  Socket socket;

  SocketClient._internal() {
    printLog("初始化SocketClient");
    _initSocket();
  }

  MessageHandler<String> messageHandler;

  PeriodicHandler periodicHandler;

  PeriodicHandler sendHeartbeatMessage;

  factory SocketClient() => _getInstance();
  static SocketClient get instance => _getInstance();
  static SocketClient _instance;

  static SocketClient _getInstance() {
    if (_instance == null) {
      _instance = SocketClient._internal();
    }
    return _instance;
  }

  Future<void> init() async {
    _initSocket();
  }

  Future<void> _initSocket() async {
    printLog("初始化Socket");
    try {
      socket = await Socket.connect(HOST, PORT, timeout: Duration(seconds: 3));
      printLog("socket连接成功");
      if(periodicHandler != null) {
        periodicHandler();
      }
      if(sendHeartbeatMessage != null) {
        sendHeartbeatMessage();
      }
    } catch (e) {
      printLog("连接错误， $e");
      Future.delayed(Duration(seconds: 2), () async {
        printLog("重试建立连接 ${DateTime.now().toLocal().toString()}");
        _initSocket();
      });
    }
    socket.listen((onData) => onDataFun(onData, (msg) {
      printLog(msg);
      if (messageHandler != null){
        messageHandler(msg);
      }
    }), onError: errorHandler, onDone: doneHandler, cancelOnError: false);
    return null;
  }

  void close() {
    printLog("关闭Socket流");
    socket?.close();
  }

  void doneHandler() {
    printLog("结束链接");
  }

  errorHandler(error) {
    printLog("监听出错，$error");
    _initSocket();
  }

  printLog(String l) {
    print("$_TAG$l");
  }

  static const _TAG = "[socket.client] ";
}

